package com.yxq.mdt.app.modules.publish.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.bottomsheet.SoundVoiceBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.personal.bean.PublishResult;
import com.yxq.mdt.app.modules.publish.ui.bean.MainPublishBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishFileList;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishListBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishTopicInfo;
import com.yxq.mdt.app.modules.publish.ui.model.MainPublishModel;
import com.yxq.mdt.app.modules.publish.ui.presenter.IMainPublishContract;
import com.yxq.mdt.app.modules.publish.ui.presenter.MainPublishPresenter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialContactAllTopicsAc;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.utils.MediaRecorderHelper;
import com.yxq.mdt.app.widgets.CheckAudioPermission;
import com.yxq.mdt.app.widgets.OssHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 发布语音
 */
public class PublishVoiceActivity extends BaseActivity<MainPublishPresenter> implements IMainPublishContract.View {
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.publish_topic)
    TextView publishTopic;
    @BindView(R.id.publish_select_circle)
    RelativeLayout publishSelectCircle;
    @BindView(R.id.publish_add_voice)
    ImageView publishAddVoice;
    @BindView(R.id.publish_del_voice)
    ImageView publishDelVoice;
    @BindView(R.id.publish_save_voice)
    LinearLayout publishSaveVoice;
    @BindView(R.id.publish_add_voice_time)
    TextView publishAddVoiceTime;
    @BindView(R.id.publish_start_play)
    RelativeLayout publishStartPlay;
    @BindView(R.id.publish_note)
    ImageView publishNote;
    @BindView(R.id.publish_voice_content)
    EditText publishVoiceContent;
    @BindView(R.id.publish_voice_content_words)
    TextView publishVoiceContentWords;
    @BindView(R.id.publish_voice_btn)
    TextView publishVoiceBtn;
    @BindView(R.id.publish_voice_content_check)
    CheckBox publishVoiceContentCheck;
    @BindView(R.id.address_text)
    TextView addressText;
    private int GOTOCIRCLE = 101;
    SoundVoiceBottomSheetDialogFragment soundVoiceBottomSheetDialogFragment;
    private MediaRecorderHelper mMediaRecorderHelper;
    private String playYime, playPath, playTimeClass;
    CountDownTimer countDownTimer;
    private String sort = "1", class2;
    private String liftText;
    private String groupId = "", TopicOfConversation = "";
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {Manifest.permission.RECORD_AUDIO};

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_voice;
    }

    @Override
    public void initView() {
        if (!TextUtils.isEmpty(getIntent().getStringExtra("CircleId"))) {
            groupId = getIntent().getStringExtra("CircleId");
        }
        addressText.setText(Hawk.get(SPKey.SP_KEY_USER_ADDRESS_CITY_NAME));
        mMediaRecorderHelper = new MediaRecorderHelper(getRecorderFilePath());
        publishSelectCircle.setOnClickListener(view -> {
            if (!TextUtils.isEmpty(publishVoiceContent.getText())) {
                if (publishVoiceContent.getText().toString().contains("#")) {
                    TopicOfConversation = publishVoiceContent.getText().toString().substring(publishVoiceContent.getText().toString().indexOf("#"), publishVoiceContent.getText().toString().lastIndexOf("#") + 1);
                    publishVoiceContent.setText(liftText);
                }
                TopicOfConversation = "";
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publishVoice", "2");
                startActivityForResult(intent, GOTOCIRCLE);
            } else {
                publishVoiceContent.setHint("想和大家分享什么呢？");
                Intent intent = new Intent(mActivity, SocialContactAllTopicsAc.class);
                intent.putExtra("publishVoice", "2");
                startActivityForResult(intent, GOTOCIRCLE);
            }

        });

        publishAddVoice.setOnClickListener(view -> {
            //检测是否有录音权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "默认无录音权限");
                if (Build.VERSION.SDK_INT >= 23) {
                    requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1001);
                }
            } else {
                if (mMediaRecorderHelper.getCurrentFilePath() != null) {
                    File file = new File(mMediaRecorderHelper.getCurrentFilePath());
                    file.delete();
                } else {
                    soundVoiceBottomSheetDialogFragment = new SoundVoiceBottomSheetDialogFragment("s");
                    soundVoiceBottomSheetDialogFragment.show(getSupportFragmentManager(), "soundVoiceBottomSheetDialogFragment");
                    soundVoiceBottomSheetDialogFragment.setSoundVoiceBottomSheetDialogFragmentTime((time, path) -> {//返回的时间和所在路径.
                        if (TextUtils.isEmpty(time)) {
                            publishAddVoiceTime.setText("");
                        } else {
                            publishAddVoiceTime.setText(time + "″");
                            playPath = path;
                            playYime = time;
                            publishAddVoice.setVisibility(View.GONE);
                            publishSaveVoice.setVisibility(View.VISIBLE);
                            publishVoiceBtn.setEnabled(true);
                        }
                    });
                }
                //有权限
                Log.i(TAG, "onRequestPermissionsResult: 申请后，是否有权限:true");
            }

        });
        publishStartPlay.setOnClickListener(view -> {
            MediaPlayerHelper.playSound(playPath);
            getTime(playYime, publishNote, publishAddVoiceTime);
            countDownTimer.start();
        });
        publishVoiceContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                publishVoiceBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                publishVoiceBtn.setTextColor(getResources().getColor(R.color.color_font_black));

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = publishVoiceContent.getText().toString();
                if (content.length() == 0) {
                    publishVoiceBtn.setBackgroundResource(R.drawable.shape_btn_lin_selector);
                    publishVoiceBtn.setTextColor(getResources().getColor(R.color.gray_pressed));
                } else {
                    publishVoiceBtn.setBackgroundResource(R.drawable.shape_button_confirm_red_selector_20);
                    publishVoiceBtn.setTextColor(getResources().getColor(R.color.color_font_black));
                }
                publishVoiceContentWords.setText(content.length() + "/" + 1000);

            }
        });
        //删除当前的录音并重新录制
        publishDelVoice.setOnClickListener(view -> {
            publishSaveVoice.setVisibility(View.GONE);
            publishAddVoice.setVisibility(View.VISIBLE);
            publishVoiceBtn.setEnabled(false);
            publishVoiceBtn.setBackgroundResource(R.drawable.shape_btn_gray_bg);
            publishVoiceBtn.setTextColor(getResources().getColor(R.color.gray_pressed));
            ToastUtils.showLong("请重新上传语音");
            playPath = null;
        });

    }

    /**
     * @param playTime  开始时间
     * @param imageView 获取当前控件
     * @param timeTv    获取显示秒数
     */
    private void getTime(String playTime, ImageView imageView, TextView timeTv) {
        imageView.setImageResource(R.mipmap.voice_note_new);
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeTv.setText(millisUntilFinished / 1000 + "″");
                publishDelVoice.setVisibility(View.GONE);
            }

            @Override
            public void onFinish() {
                timeTv.setText(Integer.parseInt(playTime) + "″");
                imageView.setImageResource(R.mipmap.voice_note);
                publishDelVoice.setVisibility(View.VISIBLE);
                countDownTimer.cancel();
            }
        };
    }


    //判断当前输入的文字跟上传的视频是否为空
    private void setContentIsNull() {
        if (playPath == null) {
            ToastUtils.showShort("请上传语音");
            return;
        }
        if (publishVoiceContent.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入内容");
            return;
        }
        showLoadingDialog();
        class2 = String.valueOf(OssHelper.getVideoVoiceTime(playPath));
        @SuppressLint("AutoDispose") Disposable disposable = Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    //好了
                    File file = new File(playPath);
                    OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP_VOICE + file.getName(), file.getPath()));
                    String url = OssHelper.getOssPrefixUrl(OssHelper.GS_APP_VOICE, file.getName());
                    emitter.onNext(url);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((String s) -> {
                    playPath = s;
                    List<PublishFileList> lists = new ArrayList<>();
                    PublishFileList l = new PublishFileList(sort, s, playYime);
                    lists.add(l);
                    PublishTopicInfo topicInfo;
                    if (publishVoiceContentCheck.isChecked()) {
                        topicInfo = new PublishTopicInfo(publishVoiceContent.getText().toString(), "6", groupId, "");
                    } else {
                        topicInfo = new PublishTopicInfo(publishVoiceContent.getText().toString(), "6", groupId, "");
                    }
                    MainPublishBean publishBean = new MainPublishBean();
                    publishBean.setGsTopicInfo(topicInfo);
                    publishBean.setFileList(lists);
                    mPresenter.onSetDoPublishList(JSON.toJSONString(publishBean));
                }, Throwable::printStackTrace);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        MediaPlayerHelper.realese();
    }

    public String getRecorderFilePath() {
        String path = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = getExternalCacheDir().getAbsolutePath();
        } else {
            path = getCacheDir().getAbsolutePath();

        }
        return path + File.separator + "Recorder";
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new MainPublishPresenter(this, new MainPublishModel());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == GOTOCIRCLE) {
                String CircleName = data.getStringExtra("CircleName");
                liftText = publishVoiceContent.getText().toString();
                if (!TextUtils.isEmpty(data.getStringExtra("CircleName"))) {
                    publishTopic.setText(CircleName);
                } else {
                    publishTopic.setText("");
                }
                TopicOfConversation = "";
                publishVoiceContent.setText(data.getStringExtra("CircleName") + liftText);
                publishVoiceContent.setSelection(publishVoiceContent.getText().length());

            }
        }
    }

    @Override
    public void onSetDoPublishSuccess(PublishListBean publishListBean) {
        hideLoadingDialog();
        showBottomToast("上传成功");
        new Handler().postDelayed(() -> {
            EventBus.getDefault().post(new PublishResult());
            finish();
        }, 200);
    }

    @Override
    public void onSetDoPublishFailed(String errMsg) {
        hideLoadingDialog();
        showBottomToast(errMsg);
    }

    @OnClick({R.id.publish_voice_btn, R.id.pub_voice_tv_user_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.publish_voice_btn:
                setContentIsNull();
                break;
            case R.id.pub_voice_tv_user_agreement:
                Intent intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PUBLIC_USER_AGREEMENT);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            //方式一校验
            boolean isHasAudioPermission = CheckAudioPermission.isHasPermission(this);
            Log.i(TAG, "申请权限完毕,当前录音权限:" + isHasAudioPermission);
            //方式二校验
            int result = 0;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    result++;
                }
            }
            if (result != permissions.length) {
                //没有权限
                showBottomToast("请先允许录音权限,请前往设置界面打开录音权限!");
                Log.i(TAG, "onRequestPermissionsResult: 申请权限完毕,当前录音权限:false");
                return;
            }

        }
    }

    /*
     * 申请录音权限*/
    public static void verifyAudioPermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);

        }
    }
}
